import 'package:flutter/material.dart';

typedef MarqueeCallback = Function(Duration);

class MarqueeWidget extends StatefulWidget {
  final Widget child;
  final MarqueeCallback callback;
  final bool autoScroller;
  final Duration? autoScrollDelay;
  final GestureTapCallback? onTap;

  const MarqueeWidget({
    Key? key,
    required this.child,
    required this.callback,
    required this.autoScroller,
    required this.autoScrollDelay,
    required this.onTap,
  }) : super(key: key);

  @override
  State<MarqueeWidget> createState() => _MarqueeWidgetState();
}

class _MarqueeWidgetState extends State<MarqueeWidget> {
  final ScrollController scrollController = ScrollController();
  final GlobalKey globalKey = GlobalKey();
  final GlobalKey sKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      if (widget.autoScroller) {
        Future.delayed(
            widget.autoScrollDelay ?? const Duration(milliseconds: 1000), () {
          autoScroll();
        });
      }
    });
  }

  void autoScroll() async {
    double sw = sKey.currentContext?.size?.width ?? 0;
    double w = globalKey.currentContext?.size?.width ?? 0;
    var duration = Duration(milliseconds: (w - sw) * 1000 ~/ 30);
    print(duration.inMilliseconds);
    await scrollController.animateTo((w - sw),
        duration: duration, curve: Curves.linear);
    widget.callback(duration);
  }

  @override
  void didUpdateWidget(covariant MarqueeWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: widget.onTap == null
          ? null
          : () {
              widget.onTap?.call();
            },
      child: IgnorePointer(
        ignoring: true,
        child: SingleChildScrollView(
          key: sKey,
          scrollDirection: Axis.horizontal,
          controller: scrollController, // Optional
          child: SizedBox(key: globalKey, child: widget.child),
        ),
      ),
    );
  }
}
